/*
 * string_util.cpp
 *
 *  Created on: 2008-9-25
 *      Author: fanliangliang
 */

#include "string_util.h"

BEGIN_NAMESPACE_TOXIC

string& trim(string& s, const string& delims /*= " "*/) {
	// trim right
	string::size_type pos = s.find_last_not_of(delims);
	if (pos == string::npos) {
		s.clear();
		return s;
	} else if (pos + 1 != s.size()) {
		s.erase(pos + 1);
	}

	// trim left
	pos = s.find_first_not_of(delims);
	if (pos == string::npos) {
		s.clear();
	} else {
		s.erase(0, pos);
	}

	return s;
}

string& ltrim(string& s, const string& delims /*= " "*/) {
	string::size_type pos = s.find_first_not_of(delims);
	if (pos == string::npos) {
		s.clear();
	} else {
		s.erase(0, pos);
	}

	return s;
}

string& rtrim(string& s, const string& delims /*= " "*/) {
	string::size_type pos = s.find_last_not_of(delims);
	if (pos == string::npos) {
		s.clear();
	} else if (pos + 1 != s.size()) {
		s.erase(pos + 1);
	}

	return s;
}

string trim(const string& s, const string& delims /*= " "*/) {
	string::size_type begin = s.find_first_not_of(delims);
	if (begin == string::npos) {
		return "";
	}

	string::size_type end = s.find_last_not_of(delims);
	return s.substr(begin, end - begin + 1);
}

string ltrim(const string& s, const string& delims /*= " "*/) {
	string::size_type pos = s.find_first_not_of(delims);
	if (pos == string::npos) {
		return "";
	} else {
		return s.substr(pos);
	}
}

string rtrim(const string& s, const string& delims /*= " "*/) {
	string::size_type pos = s.find_last_not_of(delims);
	if (pos == string::npos) {
		return "";
	} else {
		return s.substr(0, pos + 1);
	}
}

string& replace(string& s, const string& oldValue, const string& newValue) {
    size_t lenOld = oldValue.size(), lenNew = newValue.size();
    string::size_type currPos = 0, prevPos = 0;
    while ((currPos = s.find(oldValue, prevPos)) != string::npos) {
        s.replace(currPos, lenOld, newValue);
        prevPos = currPos + lenNew;
    }
    return s;
}

string& replace(string& s, const string& oldValue, size_t num, char c) {
    size_t lenOld = oldValue.size();
    string::size_type currPos = 0, prevPos = 0;
    while ((currPos = s.find(oldValue, prevPos)) != string::npos) {
        s.replace(currPos, lenOld, num, c);
        prevPos = currPos + num;
    }
	return s;
}

bool startsWith(const string& s, const string& prefix, size_t pos /*= 0*/) {
	size_t sSize = s.size();
	size_t prefixSize = prefix.size();
	return (sSize >= prefixSize + pos) && (s.compare(pos, prefixSize, prefix) == 0);
}

bool endsWith(const string& s, const string& suffix) {
	size_t sSize = s.size();
	size_t suffixSize = suffix.size();
	return sSize >= suffixSize && (s.compare(sSize - suffixSize, suffixSize, suffix) == 0);
}

END_NAMESPACE_TOXIC
